package com.yunxin.download.server.api;

import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.common.result.ResultCode;
import com.yunxin.download.server.api.request.DownloadRecordPageRequest;
import com.yunxin.download.server.api.request.UpdateDownloadRecordStatusRequest;
import com.yunxin.download.server.api.response.DownloadRecordPageResponse;
import com.yunxin.download.server.infra.constant.enums.DownloadFileStatusEnum;
import com.yunxin.download.server.infra.constant.enums.DownloadStatusEnum;
import com.yunxin.download.server.infra.repository.DownloadRecordDao;
import com.yunxin.download.server.infra.utils.DateUtils;
import com.yunxin.download.server.model.entity.DownloadRecord;
import com.yunxin.download.server.model.query.result.DownloadRecordPageCondition;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zero°
 * @since 2023-06-15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/download/record")
public class DownloadRecordController {

    private final DownloadRecordDao downloadRecordDao;

    /**
     * 分页查询下载记录
     * @param request request
     * @return PageResult<DownloadRecordPageResponse>
     */
    @PostMapping("/downloadRecordPageQuery")
    public PageResult<DownloadRecordPageResponse> downloadRecordPageQuery(@Validated @RequestBody DownloadRecordPageRequest request) {
        //每次查询都去更新过期时间  懒更新
        expireDownloadFile();
        DownloadRecordPageCondition downloadRecordPageCondition = new DownloadRecordPageCondition();
        downloadRecordPageCondition.setDownloaderName(request.getDownloaderName());
        long total = downloadRecordDao.countDownloadRecordPageQuery(downloadRecordPageCondition);
        if (total == 0) {
            return PageResult.success(Collections.emptyList(), total);
        }
        int pageNum = (Objects.isNull(request.getPageNum()) || request.getPageNum() <= 0) ? 1 : request.getPageNum();
        int pageSize = (Objects.isNull(request.getPageSize()) || request.getPageSize() <= 0) ? 1 : request.getPageSize();
        int offset = (pageNum - 1) * pageSize;
        downloadRecordPageCondition.setOffset(offset);
        downloadRecordPageCondition.setPageSize(pageSize);
        List<DownloadRecord> list = downloadRecordDao.downloadRecordPageQuery(downloadRecordPageCondition);
        List<DownloadRecordPageResponse> responses = list.stream().map(x -> {
            DownloadRecordPageResponse response = new DownloadRecordPageResponse();
            response.setId(x.getId());
            response.setDownloadTime(x.getDownloadTime());
            response.setDownloadFileName(x.getDownloadFileName());
            response.setDownloadFileUrl(x.getDownloadFileUrl());
            response.setDownloadFileStatus(x.getDownloadFileStatus());
            response.setDownloadFileStatusStr(DownloadFileStatusEnum.getByStatus(x.getDownloadFileStatus()).getDescription());
            response.setDownloadStatus(x.getDownloadStatus());
            response.setDownloadStatusStr(DownloadStatusEnum.getByStatus(x.getDownloadStatus()).getDescription());
            return response;
        }).toList();
        return PageResult.success(responses, total);
    }

    /**
     * 获取未下载且未过期的下载记录条数
     * @param downloaderName downloaderName
     * @return Result<Integer>
     */
    @GetMapping("/getUnDownloadCount")
    public Result<Integer> getUnDownloadCount(@RequestParam("downloaderName") String downloaderName) {
        int count = downloadRecordDao.getUnDownloadCount(downloaderName);
        return Result.success(count);
    }

    /**
     * 更新下载记录下载状态
     * @param request request
     * @return Result<Boolean>
     */
    @PostMapping("/updateMethodRecordStatus")
    public Result<Boolean> updateMethodRecordStatus(@Validated @RequestBody UpdateDownloadRecordStatusRequest request) {
        DownloadRecord downloadRecord = downloadRecordDao.selectByPrimaryKey(request.getId());
        if (Objects.isNull(downloadRecord)) {
            throw new BusinessException(ResultCode.DATA_NO_EXIST_ERROR);
        }
        downloadRecord.setDownloadStatus(1);
        downloadRecord.setVersion(downloadRecord.getVersion() + 1);
        downloadRecord.setEditTime(new Date());
        int count = downloadRecordDao.updateByPrimaryKeySelective(downloadRecord);
        return Result.success(count > 0);
    }

    /**
     * 过期文件
     */
    public void expireDownloadFile(){
        Date startTime = DateUtils.X.addDay(new Date(), -3);
        List<DownloadRecord> list = downloadRecordDao.expireList(startTime);
        if (list.isEmpty()) {
            return ;
        }
        List<Long> ids = list.stream().map(DownloadRecord::getId).toList();
        // 删除阿里云文件?
        downloadRecordDao.batchUpdateDownloadFileStatus(ids, DownloadFileStatusEnum.EXPIRED.getStatus());
    }
}
